# 批量转换一个目录中所有的文件的编码(已支持递归修改目录中的文件),本例将自动检测其文件编码并转换为UTF-8
import os
import codecs
folder=r'D:\IdeaProjects\JavaBook'

SEPERATOR=os.sep

def convert_file(folder):
	lst = os.listdir(folder)
	for file in lst:
		try:
			filename_in=folder+SEPERATOR+file
			if os.path.isfile(filename_in):
				filename_out=filename_in
				with codecs.open(filename=filename_in, mode='r') as fi:
					data = fi.read()
				with open(filename_out, mode='w', encoding='utf-8') as fo:
					fo.write(data)
					fo.close()
			elif os.path.isdir(filename_in):
				convert_file(filename_in)
		except(UnicodeDecodeError):
			pass


if __name__=="__main__":
	convert_file(folder)
